const mongodb = require('mongodb');

const getdb = require('../utils/database').getdb;

const ObjectId = mongodb.ObjectId;

module.exports = class Product {
    constructor(id, title, imageUrl, price, description) {
        this._id = new mongodb.ObjectId(id || 0);
        this.title = title;
        this.imageUrl = imageUrl;
        this.price = price;
        this.description = description;
    }
    save() {
        return getdb().collection('products')
        .updateOne(
            { _id: this._id },
            {
                $set: {
                    title: this.title,
                    imageUrl: this.imageUrl,
                    price: this.price,
                    description: this.description
                }
            },
            {
                upsert: true
            }
        )
    }
    static fetchAll() {
        return getdb().collection('products')
        .find().toArray()
    }
    static findById(prodId) {
        return getdb().collection('products')
        .findOne({ _id: new ObjectId(prodId) })
    }
    static delById(prodId) {
        return getdb().collection('products')
        .deleteOne({ _id: new ObjectId(prodId) })
    }
}